package frame.form;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class Struts_config {

	public Struts_config() {

	}

	public static Map<String, XmlBean> getConfig(String path) {
		SAXBuilder builder = new SAXBuilder();
		Map<String, XmlBean> configMaps = new HashMap<String, XmlBean>();
		try {
			Document doc = builder
					.build(path);
			Element root = doc.getRootElement();
			Element mappings = root.getChild("action-mapping");
			List<Element> actions = mappings.getChildren();
			Element formbeans = root.getChild("formbeans");
			List<Element> beans = formbeans.getChildren();
			for (Element action : actions) {
				List<Element> forwards = action.getChildren();
				XmlBean actionBean = new XmlBean();
				String actionName = action.getAttributeValue("name");
				actionBean.setBeanName(actionName);
				String actionhandler = action.getAttributeValue("handler");
				actionBean.setHandler(actionhandler);
				String actionpath = action.getAttributeValue("path");
				actionBean.setPath(actionpath);
				for (Element bean : beans) {
					if (actionName.equals(bean.getAttributeValue("name"))) {
						String formClass = bean.getAttributeValue("class");
						actionBean.setFormClass(formClass);
					}
				}
				Map<String, String> map = new HashMap<String, String>();
				for (Element forward : forwards) {
					String forward_name = forward.getAttributeValue("name");
					String forward_value = forward.getAttributeValue("value");
					map.put(forward_name, forward_value);
				}
				actionBean.setActionForward(map);
				configMaps.put(actionpath, actionBean);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return configMaps;
	}

	public static void main(String[] args) {
		Map<String, XmlBean> m  = getConfig("WebContent/WEB-INF/struts-config.xml");
		Set<String> sets = m.keySet();
		for(Iterator<String> it = sets.iterator(); it.hasNext();){
			String key = it.next();
			XmlBean bean = m.get(key);
			System.out.println(key);
			System.out.println(bean.getBeanName() + "===" + bean.getFormClass() + "====" + bean.getHandler() + "===" + bean.getPath());
		}
	}

}
